<?php

namespace App\Console\Commands;

use App\Libs\BLogger;
use App\Libs\Jidi;
use App\Models\ConvertUrls;
use App\Models\Product;
use Illuminate\Console\Command;

use DB;

class GetGoodsFromJidi extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'get-goods-from-jidi';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '从基地获取商品信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $jidi = new Jidi();
        $productModel = new Product();

        $page = 0;
        while (1) {
            try {
                $page++;
                $accessToken = $jidi->getToken();
                $products = curlGet($jidi->getProductsUrl() . "?token={$accessToken}&per=200&page={$page}&sort=3");
                $products = json_decode($products);
                if ($products) {
                    if ($products->status == 200) {
                        foreach ($products->proList->data as $product) {
                            $tbid = $product->taobao_id;

                            $saveData = [
                                'class_id' => $product->class_id,
                                'tbid' => $product->taobao_id,
                                'goods_name' => $product->buss_name,
                                'taobao_title' => null,
                                'goods_pic' => $product->pic,
                                'coupon_link' => $product->couponLink,
                                'coupon_surplus' => $product->coupon_surplus,
                                'coupon_count' => $product->coupon_count,
                                'coupon_received' => $product->coupon_received,
                                'coupon_end' => $product->coupon_end,
                                'quan_fee' => $product->quan_fee * 100,
                                'guid_content' => $product->guid_content,
                                'sales' => $product->sales,
                                'tmall' => $product->tmall,
                                'me' => $product->me,
                                'is_merchants' => $product->is_merchants,
                                'commission_rate' => $product->commission_rate,
                                'commission_type' => $product->commission_type,
                                'taoke_price' => (int)$product->juanhou * 100,
                                'sales_price' => (int)$product->shoujia * 100,
                                'sort' => 2,
                                'is_top' => 0,
                                'update_time' => date('Y-m-d H:i:s', time()),
                                'delete_time' => null
                            ];
                            DB::beginTransaction();
                            try {
                                $goodsData = DB::table($productModel->getTable())->where('tbid', $tbid)->first();
                                if ($goodsData) {
                                    $id = $goodsData->id;
                                    if ($goodsData->sort > 2) {
                                        $saveData['sort'] = $goodsData->sort;
                                    }
                                    if (DB::table($productModel->getTable())->where('tbid', $tbid)->update($saveData) === false) {
                                        BLogger::getLogger('GET_GOODS')->info("商品--{$product->taobao_id}--更新失败");
                                        DB::rollBack();
                                        throw new \Exception("商品--{$product->taobao_id}--更新失败");
                                    }
                                } else {
                                    $saveData['create_time'] = date('Y-m-d H:i:s', time());
                                    $id = DB::table($productModel->getTable())->insertGetId($saveData);
                                    if (!$id) {
                                        BLogger::getLogger('GET_GOODS')->info("商品--{$product->taobao_id}--添加失败");
                                        DB::rollBack();
                                        throw new \Exception("商品--{$product->taobao_id}--添加失败");
                                    }
                                }

                                if ($id) {
                                    if ($productModel->updateEsData($id, $saveData)) {
                                        BLogger::getLogger('GET_GOODS')->info("商品--{$product->taobao_id}--更新到es数据成功");
                                    } else {
                                        BLogger::getLogger('GET_GOODS')->info("商品--{$product->taobao_id}--更新到es数据失败");
                                    }
                                }

                                $convertUrlModel = new ConvertUrls();
                                if (\DB::table($convertUrlModel->getTable())->where('tbid', $tbid)->delete() === false) {
                                    \DB::rollBack();
                                    BLogger::getLogger('GET_GOODS')->info("已转的链接--{$tbid}--删除失败");
                                    throw new \Exception("已转的链接--{$tbid}--删除失败");
                                }

                                DB::commit();
                                BLogger::getLogger('GET_GOODS')->info("商品--{$product->taobao_id}--更新/添加成功");
                            } catch (\Exception $e) {
                                BLogger::getLogger('GET_GOODS')->info($e);
                                DB::rollBack();
                            }
                        }
                    } else if ($products->status == 201) {
                        BLogger::getLogger('GET_GOODS')->info('数据为空');
                    }

                    if ($products->proList->last_page < $page) {
                        BLogger::getLogger('GET_GOODS')->info("数据更新完成---总页数{$page}");
                    }
                    sleep(rand(10, 60));
                    if ($page >= 50) {
                        $page = 0;
                        sleep(rand(600, 3600));
                    }
                } else {
                    $page = 0;
                    sleep(rand(300, 900));
                    BLogger::getLogger('GET_GOODS')->info("获取基地商品列表失败");
                }
            }catch (\Exception $exception){
                BLogger::getLogger('GET_GOODS')->info($exception);
            }
        }
    }
}
